import { uniqBy } from 'lodash-es'
import { useUserAllStore } from './all/store'
import {
	TranslatorAllToSimple,
	getItemInAll,
	getSpeakerManager,
	initUser,
	setCascadeInAll,
	setSearchStatusInAll,
	setSearchStatusInSimple,
} from './utils'
import { UserModel } from './interface'
import { useBasicInfoStore } from '../basicInfo/store'
import { useUserOftenStore } from './often/store'
import { useUserStore } from './store'
import { useUserInteractiveStore } from './interactive/store'
import { Confirm } from '@/components/Alert'
import { t } from 'i18next'
import { ITab, useCreateContentStore } from '../../store'
import { useMeetingPollStore } from '../poll/store'
import { useMeetingMixStore } from '../mix/store'
import { useMeetingLiveVideoStore } from '../liveVideo/store'
import { useMeetingDcsStore } from '../dcs/store'
import { useMeetingVmpStore } from '../vmp/store'
import { useMeetingTVWallStore } from '../tvwall/store'
import { UserEntity } from '@/api/create/interface'
import { useMeetingParamsStore } from '../meetingParams/store'
import {
	setDcsList,
	setKcList,
	setMixList,
	setPollList,
	setTvwallPollList,
	setVipList,
	setVlList,
	setVmpPollList,
	vipSort2Users,
} from '../../store.combine'
import { SelectMtEntity } from '@/components/AddMt/translator'
import { fetchCascadeData } from '@/api/create'
import { ActionType } from '@/components/List'
import { dealDrop, listOrderClick } from '@/utils/listSlice'
import { Poll } from '../vmp/VmpPoll/interface'
import { refreshTvwallMembers } from '../tvwall/store.combine'

function changeSpeakerManger() {
	//最后，设置发言方，管理方
	const { speakerList, managerList } = getSpeakerManager(useUserAllStore.getState().tree, {
		superMtNum: useBasicInfoStore.getState().superMtNum,
	})
	useBasicInfoStore.setState({ speakerList, managerList })

	//不在右侧人员列表就需要将其设置成无
	const prevSpeaker = useBasicInfoStore.getState().speaker
	const prevManager = useBasicInfoStore.getState().manager
	if (speakerList.findIndex((x) => x.uid === prevSpeaker.uid) < 0) {
		useBasicInfoStore.setState({ speaker: initUser })
	}
	if (managerList.findIndex((x) => x.uid === prevManager.uid) < 0) {
		useBasicInfoStore.setState({ manager: initUser })
	}
}

export const addCheckedFromAllTree = () => {
	const tree = useUserAllStore.getState().tree
	const superMtNum = useBasicInfoStore.getState().superMtNum

	let result: UserModel[] = []
	if (superMtNum) {
		for (const item of tree) {
			if (item.status.checked && item.mcc.account_type !== 10) {
				//超大方只有本级
				item.status.isInteractive = true
				item.mcc.interactive_mt = 1
				result.push(item)
			}
		}
	} else {
		getItemInAll(tree, (item) => {
			//同时排除了简单级联
			if (item.status.checked && item.mcc.account_type !== 10) {
				item.status.isOften = true
				result.push(item)
			}
		})
	}

	//更新all
	useUserAllStore.setState({ tree: [...tree] })

	//更新often/interactive
	let simpleStore = superMtNum ? useUserInteractiveStore : useUserOftenStore
	const preList = simpleStore.getState().list
	const keywords = useUserStore.getState().keywords
	let list = uniqBy([...preList, ...TranslatorAllToSimple(result)], (val) => val.uuid)
	setSearchStatusInSimple(list, keywords)
	simpleStore.setState({ list })
}

export const addItemInSimple = (uuid: string) => {
	const tree = useUserAllStore.getState().tree
	const superMtNum = useBasicInfoStore.getState().superMtNum

	let result: UserModel[] = []
	if (superMtNum) {
		for (const item of tree) {
			if (item.uuid === uuid) {
				//超大方只有本级
				item.status.isInteractive = true
				item.mcc.interactive_mt = 1
				result.push(item)
			}
		}
	} else {
		getItemInAll(tree, (item) => {
			//同时排除了简单级联
			if (item.uuid === uuid) {
				item.status.isOften = true
				result.push(item)
			}
		})
	}
	//更新all
	useUserAllStore.setState({ tree: [...tree] })

	//更新often/interactive
	let simpleStore = superMtNum ? useUserInteractiveStore : useUserOftenStore
	const preList = simpleStore.getState().list
	const keywords = useUserStore.getState().keywords
	let list = uniqBy([...preList, ...TranslatorAllToSimple(result)], (val) => val.uuid)
	setSearchStatusInSimple(list, keywords)
	simpleStore.setState({ list })

	if (superMtNum) {
		//更新发言方管理方
		changeSpeakerManger()
	}
}

export const removeCheckedInSimple = () => {
	const superMtNum = useBasicInfoStore.getState().superMtNum
	let simpleStore = superMtNum ? useUserInteractiveStore : useUserOftenStore
	const preList = simpleStore.getState().list
	let list = preList.filter((x) => !x.status.checked)
	simpleStore.setState({ list })

	//更新all
	const tree = useUserAllStore.getState().tree
	const uuids = list.map((x) => x.uuid)
	if (superMtNum) {
		for (const item of tree) {
			if (uuids.includes(item.uuid)) {
				item.status.isInteractive = true
				item.mcc.interactive_mt = 1
			} else {
				item.status.isInteractive = false
				item.mcc.interactive_mt = 0
			}
		}
	} else {
		getItemInAll(tree, (item) => {
			if (uuids.includes(item.uuid)) {
				item.status.isOften = true
			} else {
				item.status.isOften = false
			}
		})
	}

	useUserAllStore.setState({ tree: [...tree] })
}

export const removeCheckedInAll = () => {
	const tree = useUserAllStore.getState().tree
	//删除只能删本级的，下级模板的终端不可删除; 会议室的删除需要额外外部确认
	let _tree = tree.filter((x) => !x.status.checked || x.mcc.account_type === 2)
	let removeUuids = tree.filter((x) => x.status.checked && x.mcc.account_type !== 2).map((x) => x.uuid)
	useUserAllStore.setState({ tree: _tree })

	//更新often/interactive
	const superMtNum = useBasicInfoStore.getState().superMtNum
	let simpleStore = superMtNum ? useUserInteractiveStore : useUserOftenStore
	const preList = simpleStore.getState().list
	let list = preList.filter((x) => !removeUuids.includes(x.uuid))
	simpleStore.setState({ list })

	//需要删除的会议室，传递给外部
	let rooms = tree.filter((x) => x.status.checked && x.mcc.account_type === 2)
	if (rooms.length > 0) {
		Confirm(t('您确定要释放锁定和预定的会议室吗？'), () => {
			useBasicInfoStore.setState({ _isSearchRoomDialogShow: true })
		})
	}

	//更新发言方管理方
	changeSpeakerManger()
}

export const removeItemInAll = (actualUuid: string) => {
	const tree = useUserAllStore.getState().tree
	let _tree = tree.filter((x) => x.attr.actualUuid !== actualUuid)
	let removeItem = tree.find((x) => x.attr.actualUuid === actualUuid)

	//更新often/interactive
	if (removeItem) {
		//需要删除的会议室，传递给外部
		if (removeItem.mcc.account_type === 2) {
			Confirm(t('您确定要释放锁定和预定的会议室吗？'), () => {
				useBasicInfoStore.setState({ _isSearchRoomDialogShow: true })
			})
		} else {
			useUserAllStore.setState({ tree: _tree })
			const superMtNum = useBasicInfoStore.getState().superMtNum
			let simpleStore = superMtNum ? useUserInteractiveStore : useUserOftenStore
			const preList = simpleStore.getState().list
			let list = preList.filter((x) => removeItem?.uuid !== x.uuid) //把下级终端设为的常用一样的全删了
			simpleStore.setState({ list })
		}
	}

	//更新发言方管理方
	changeSpeakerManger()
}

export const removeItemInSimple = (uuid: string) => {
	const superMtNum = useBasicInfoStore.getState().superMtNum
	let simpleStore = superMtNum ? useUserInteractiveStore : useUserOftenStore
	const preList = simpleStore.getState().list
	let list = preList.filter((x) => x.uuid !== uuid)
	simpleStore.setState({ list })

	//更新全部终端的状态
	const tree = useUserAllStore.getState().tree
	if (superMtNum) {
		for (const item of tree) {
			if (item.uuid === uuid) {
				item.status.isInteractive = false
				item.mcc.interactive_mt = 0
			}
		}
	} else {
		getItemInAll(tree, (item) => {
			if (item.uuid === uuid) {
				item.status.isOften = false
			}
		})
	}
	useUserAllStore.setState({ tree: [...tree] })
	if (superMtNum) {
		//更新发言方管理方
		changeSpeakerManger()
	}
}

export const toggleCheckedAllInAll = (flag: boolean) => {
	const tree = useUserAllStore.getState().tree

	//todo 全选 + 搜索时全选，选到会议（是否等于选了下级），选下级终端等等有点问题
	getItemInAll(tree, (item) => {
		if (item.status.isMatchSearch) {
			item.status.checked = flag
		}
	})
	useUserAllStore.setState({ tree: [...tree] })
}

export const toggleCheckedAllInSimple = (flag: boolean) => {
	const superMtNum = useBasicInfoStore.getState().superMtNum
	let simpleStore = superMtNum ? useUserInteractiveStore : useUserOftenStore
	const preList = simpleStore.getState().list
	let list = preList.map((x) => {
		x.status.checked = flag
		return x
	})
	simpleStore.setState({ list })
}

export const searchUser = (keywords: string) => {
	const superMtNum = useBasicInfoStore.getState().superMtNum
	const tree = useUserAllStore.getState().tree
	setSearchStatusInAll(tree, keywords)
	//更新all
	useUserAllStore.setState({ tree: [...tree] })
	//更新often/interactive
	let simpleStore = superMtNum ? useUserInteractiveStore : useUserOftenStore
	const list = simpleStore.getState().list
	setSearchStatusInSimple(list, keywords)
	simpleStore.setState({ list: [...list] })
}

export const orderInAll = (type: ActionType) => {
	const curIsCascade = useMeetingParamsStore.getState().simpleCascade === 1
	const tree = useUserAllStore.getState().tree
	if (curIsCascade) {
		//级联会议在下，终端在上（简单级联会议当普通终端）
		const prevUsers = tree.filter((x) => x.mcc.account_type !== 10 || x.attr.isSimpleCascade)
		const prevMeetings = tree.filter((x) => x.mcc.account_type === 10 && !x.attr.isSimpleCascade)
		let users = listOrderClick(prevUsers, type)
		let meetings = listOrderClick(prevMeetings, type)
		useUserAllStore.setState({ tree: [...users, ...meetings] })
	} else {
		const result = listOrderClick(tree, type)
		useUserAllStore.setState({ tree: result })
	}

	//order后更新发言方管理方下拉列表
	const { speakerList, managerList } = getSpeakerManager(useUserAllStore.getState().tree, {
		superMtNum: useBasicInfoStore.getState().superMtNum,
	})
	useBasicInfoStore.setState({ speakerList, managerList })
}

export const dropInAll = ({ user, dropIndex }: { user: Omit<UserModel, 'children'>; dropIndex: number }) => {
	const tree = useUserAllStore.getState().tree

	let _user: UserModel | null = null
	getItemInAll(tree, (item) => {
		if (item.attr.actualUuid === user.attr.actualUuid) {
			_user = item
			return false
		}
	})
	if (!_user) return

	let result = dealDrop(tree, { mts: [_user], dropIndex, isOther: false }, 'uuid')

	const curIsCascade = useMeetingParamsStore.getState().simpleCascade === 1
	if (curIsCascade) {
		//级联会议在下，终端在上（简单级联会议当普通终端）
		const prevUsers = result.filter((x) => x.mcc.account_type !== 10 || x.attr.isSimpleCascade)
		const prevMeetings = result.filter((x) => x.mcc.account_type === 10 && !x.attr.isSimpleCascade)
		result = [...prevUsers, ...prevMeetings]
	}
	useUserAllStore.setState({ tree: result })

	//order后更新发言方管理方下拉列表
	const { speakerList, managerList } = getSpeakerManager(useUserAllStore.getState().tree, {
		superMtNum: useBasicInfoStore.getState().superMtNum,
	})
	useBasicInfoStore.setState({ speakerList, managerList })
}

export const addToList = ({ type, tab }: { type: ITab; tab: 'all' | 'often' | 'interactive' }) => {
	const tree = useUserAllStore.getState().tree
	const superMtNum = useBasicInfoStore.getState().superMtNum
	let simpleStore = superMtNum ? useUserInteractiveStore : useUserOftenStore
	const simpleList = simpleStore.getState().list
	switch (type) {
		case 'basic': //VIP
			{
				const vipList = useBasicInfoStore.getState().vipList
				let checkedList = []
				if (tab === 'all') {
					checkedList = tree.filter((x) => x.status.checked)
				} else {
					checkedList = simpleList.filter((x) => x.status.checked)
				}
				setVipList([...vipList, ...checkedList.map((x) => x.mcc)])
				vipSort2Users()
			}
			break
		case 'poll': //点名 轮询
			{
				const enablePoll = useMeetingPollStore.getState().enablePoll
				const list = useMeetingPollStore.getState().memberList
				if (!enablePoll) return

				let checkedList: { mcc: UserEntity }[] = []
				if (tab === 'all') {
					getItemInAll(tree, (x) => {
						if (x.status.checked) {
							checkedList.push(x)
						}
					})
				} else {
					checkedList = simpleList.filter((x) => x.status.checked)
				}
				setPollList([...list, ...checkedList.map((x) => x.mcc)])
			}
			break
		case 'mix': //混音
			{
				const enable = useMeetingMixStore.getState().enable
				const mode = useMeetingMixStore.getState().mode
				const list = useMeetingMixStore.getState().members
				if (!enable || mode !== 2) return

				let checkedList: { mcc: UserEntity }[] = []
				if (tab === 'all') {
					getItemInAll(tree, (x) => {
						if (x.status.checked) {
							checkedList.push(x)
						}
					})
				} else {
					checkedList = simpleList.filter((x) => x.status.checked)
				}
				setMixList([...list, ...checkedList.map((x) => x.mcc)])
			}
			break
		case 'vl': //直播
			{
				const enable = useMeetingLiveVideoStore.getState().enable_live
				const list = useMeetingLiveVideoStore.getState().live_members
				if (!enable) return

				let checkedList = []
				if (tab === 'all') {
					checkedList = tree.filter((x) => x.status.checked)
				} else {
					checkedList = simpleList.filter((x) => x.status.checked)
				}
				setVlList([...list, ...checkedList.map((x) => x.mcc)])
			}
			break
		case 'dcs': //数据会议
			{
				const enable = useMeetingDcsStore.getState().enable
				const mode = useMeetingDcsStore.getState().mode
				const list = useMeetingDcsStore.getState().dcs_members

				if (!enable || mode !== 1) return

				let checkedList: { mcc: UserEntity }[] = []
				if (tab === 'all') {
					getItemInAll(tree, (x) => {
						if (x.status.checked) {
							checkedList.push(x)
						}
					})
				} else {
					checkedList = simpleList.filter((x) => x.status.checked)
				}
				setDcsList([...list, ...checkedList.map((x) => x.mcc)])
			}
			break
		case 'params': //追呼列表
			{
				const list = useMeetingParamsStore.getState().keep_calling_members
				let checkedList = []
				if (tab === 'all') {
					checkedList = tree.filter((x) => x.status.checked)
				} else {
					checkedList = simpleList.filter((x) => x.status.checked)
				}

				setKcList([...list, ...checkedList.map((x) => x.mcc)])
			}
			break
		case 'vmp': //画面合成
			{
				const mode = useMeetingVmpStore.getState().mode

				if (mode !== 3 && mode !== 4) return

				let checkedList = []

				if (tab === 'all') {
					checkedList = tree.filter((x) => x.status.checked)
				} else {
					checkedList = simpleList.filter((x) => x.status.checked)
				}
				const list = useMeetingVmpStore.getState().pollMembers || []
				//todo vmp
				setVmpPollList([...list, ...checkedList.map((x) => x.mcc)])
			}
			break
		case 'tvwall': //电视墙
			{
				const enable = useMeetingTVWallStore.getState().enable
				const mode = useMeetingTVWallStore.getState().mode

				if (!enable || mode !== 2) return

				let checkedList = []

				if (tab === 'all') {
					checkedList = tree.filter((x) => x.status.checked)
				} else {
					checkedList = simpleList.filter((x) => x.status.checked)
				}
				const list = useMeetingTVWallStore.getState().pollMembers || []
				setTvwallPollList([...list, ...checkedList.map((x) => x.mcc)])
			}
			break
		default:
			break
	}
}

interface IUserCascade {
	users: Required<Omit<SelectMtEntity, 'meetingType'>>[]
	cascadeMap?: {
		[key: string]: 0 | 1 // 0:简单级联， 1：合并级联
	}
}

function deepCascade(rootList: UserEntity[], source: { [key: string]: UserEntity[] }) {
	/**获取级联数据 */
	let result = [...rootList]
	for (let i = 0; i < rootList.length; i++) {
		let current = rootList[i]
		if (current.account_type === 10) {
			let r = deepCascade(source[current.account], source)
			result.push(...r)
		}
	}
	return result
}

async function setSubCascade(cascades: string[]) {
	const { meetingMoid, isTemplate } = useCreateContentStore.getState()
	const res = await fetchCascadeData(isTemplate, cascades, meetingMoid)
	let isSimpleMap: { [key: string]: 0 | 1 } = {}
	let mts: { [key: string]: UserEntity[] } = {}
	res.forEach((item) => {
		isSimpleMap[item.e164] = item.is_simple
		mts[item.e164] = item.mts
	})
	//提前将下下级等递归处理好
	let _result: { [key: string]: UserEntity[] } = {}
	for (let i = 0; i < cascades.length; i++) {
		let key = cascades[i]
		let result = deepCascade(mts[key] ?? [], mts)
		_result[key] = result
	}
	//变成级联的结构
	const tree = useUserAllStore.getState().tree
	setCascadeInAll(tree, { isSimpleMap, mts: _result })
	//设置搜索 (keywords取最新的)
	setSearchStatusInAll(tree, useUserStore.getState().keywords)
	//设置 often/interactive 标志;
	if (useBasicInfoStore.getState().superMtNum) {
		const ids = useUserInteractiveStore.getState().list.map((x) => x.uuid)
		for (const item of tree) {
			const match = ids.includes(item.uuid)
			item.status.isInteractive = match
			item.mcc.interactive_mt = match ? 1 : 0
		}
	} else {
		const ids = useUserOftenStore.getState().list.map((x) => x.uuid)
		getItemInAll(tree, (item) => {
			item.status.isOften = ids.includes(item.uuid)
		})
	}
	useUserAllStore.setState({ tree: [...tree] })
}

/** 添加与会方增加/更改 */
export const addFromAddMt = async ({ users, cascadeMap }: IUserCascade) => {
	//先渲染一波人员，如有级联下级，等接口回来再渲染下级
	//数据处理
	let allUsers: UserModel[] = users.map((x) => {
		return {
			mcc: {
				account: x.account,
				account_type: x.accountType,
				name: x.name,

				portrait: x.portrait,
				protocol: x.protocol,
				bitrate: x.bitrate,
				interactive_mt: x.interactiveMt,
				e164: x.e164,
			},
			status: {
				checked: false,
				isOpen: false,
				isMatchSearch: true,
				isOften: !!x.oftenMt, //设置 often 标志;
				isInteractive: !!x.interactiveMt, //设置 interactive 标志;
			},
			attr: {
				isSimpleCascade: x.accountType === 10 && cascadeMap ? cascadeMap[`${x.account}`] === 0 : false,
				actualUuid: `${x.accountType}$$${x.account}`,
			},
			uuid: `${x.accountType}$$${x.account}`,
			nestingLevel: 0,
			parentId: '',
			children: [],
		}
	})
	allUsers = [
		...allUsers.filter((x) => x.mcc.account_type !== 10),
		...allUsers.filter((x) => x.mcc.account_type === 10),
	]
	//设置搜索
	const keywords = useUserStore.getState().keywords
	setSearchStatusInAll(allUsers, keywords)
	useUserAllStore.setState({ tree: allUsers })

	if (useBasicInfoStore.getState().superMtNum) {
		let list = TranslatorAllToSimple(allUsers.filter((x) => x.status.isInteractive))
		setSearchStatusInSimple(list, keywords)
		useUserInteractiveStore.setState({ list })
	} else {
		let list = TranslatorAllToSimple(allUsers.filter((x) => x.status.isOften))
		setSearchStatusInSimple(list, keywords)
		useUserOftenStore.setState({ list })
	}

	//合并级联请求下级
	const curIsCascade = useMeetingParamsStore.getState().simpleCascade === 1
	if (curIsCascade && cascadeMap) {
		const cascades = Object.keys(cascadeMap).filter((x) => cascadeMap[x] === 1)
		await setSubCascade(cascades)
	}

	//最后，设置发言方，管理方
	changeSpeakerManger()
}

/** 会议室增加 */
export const addRooms = (rooms: UserEntity[]) => {
	const tree = useUserAllStore.getState().tree
	const superMtNum = useBasicInfoStore.getState().superMtNum
	let simpleStore = superMtNum ? useUserInteractiveStore : useUserOftenStore
	const uuids = simpleStore.getState().list.map((x) => x.uuid)
	let _rooms: UserModel[] = rooms.map((x) => {
		//判断下是否存在于 often/interactive
		let isIn = uuids.includes(`${x.account_type}$$${x.account}`)
		return {
			mcc: { ...x, interactive_mt: superMtNum && isIn ? 1 : 0 },
			status: {
				checked: false,
				isOpen: false,
				isMatchSearch: true,
				isOften: !superMtNum && isIn, //设置 often 标志;
				isInteractive: superMtNum && isIn, //设置 interactive 标志;
			},
			attr: {
				isSimpleCascade: false,
				actualUuid: `${x.account_type}$$${x.account}`,
			},
			uuid: `${x.account_type}$$${x.account}`,
			nestingLevel: 0,
			parentId: '',
			children: [],
		}
	})

	let allUsers = uniqBy(
		[...tree.filter((x) => x.mcc.account_type !== 10), ..._rooms, ...tree.filter((x) => x.mcc.account_type === 10)],
		(val) => val.uuid
	)
	//设置搜索
	const keywords = useUserStore.getState().keywords
	setSearchStatusInAll(allUsers, keywords)
	useUserAllStore.setState({ tree: allUsers })

	//最后，设置发言方，管理方
	changeSpeakerManger()
}

/** 会议室移除 */
export const removeAllRooms = () => {
	const tree = useUserAllStore.getState().tree
	let roomsUuid = tree.filter((x) => x.mcc.account_type === 2).map((x) => x.uuid)

	let noRooms = tree.filter((x) => x.mcc.account_type !== 2)

	useUserAllStore.setState({ tree: noRooms })

	//更新 often/interactive
	const superMtNum = useBasicInfoStore.getState().superMtNum
	let simpleStore = superMtNum ? useUserInteractiveStore : useUserOftenStore
	const preList = simpleStore.getState().list
	let list = preList.filter((x) => !roomsUuid.includes(x.uuid))
	simpleStore.setState({ list })

	//更新发言方管理方
	changeSpeakerManger()

	//移除会议室，会重置整个会管的所有列表（vip,轮询等） [直播通知除外]，移除其中的会议室的列表项
	//vip
	const vipList = useBasicInfoStore.getState().vipList.filter((x) => x.account_type !== 2)
	useBasicInfoStore.setState({ vipList })
	//dcs
	const dcs_members = useMeetingDcsStore.getState().dcs_members.filter((x) => x.account_type !== 2)
	useMeetingDcsStore.setState({ dcs_members })
	//mix
	const members = useMeetingMixStore.getState().members.filter((x) => x.account_type !== 2)
	useMeetingMixStore.setState({ members })
	//poll
	const memberList = useMeetingPollStore.getState().memberList.filter((x) => x.account_type !== 2)
	useMeetingPollStore.setState({ memberList })
	//追呼
	const keep_calling_members = useMeetingParamsStore
		.getState()
		.keep_calling_members.filter((x) => x.account_type !== 2)
	useMeetingParamsStore.setState({ keep_calling_members })
	//todo vmp vmpPoll tvwall tvwallPoll
	let vmpMembers = useMeetingVmpStore.getState().members
	vmpMembers = vmpMembers.filter((x) => {
		if (x.member_type === 1 && x.account_type === 2) {
			return false
		} else if (x.member_type === 6 && x.poll?.members && x.poll?.members.length > 0) {
			x.poll.members = x.poll.members.filter((x) => x.account_type !== 2)
		}
		return true
	})
	useMeetingVmpStore.setState({ members: vmpMembers })
	let vmpPollMembers = useMeetingVmpStore.getState().poll?.members
	if (vmpPollMembers) {
		vmpPollMembers = vmpPollMembers.filter((x) => x.account_type !== 2)
		useMeetingVmpStore.setState((v) => ({ poll: { ...v.poll, members: vmpPollMembers } as Poll }))
	}
	refreshTvwallMembers()
}

/**移除不在全部终端内的终端，刷新整个会管的所有列表（vip,轮询等） [直播通知除外]， */
export const refreshList = () => {
	const tree = useUserAllStore.getState().tree
	let selectUsersAccount$$AccountType: string[] = []
	let selectUsersE164: (string | undefined)[] = []
	getItemInAll(tree, (item) => {
		if (item.mcc.account_type !== 10) {
			selectUsersAccount$$AccountType.push(`${item.mcc.account_type}$$${item.mcc.account}`)
			selectUsersE164.push(item.mcc.e164)
		}
	})

	function refresh(members: UserEntity[]) {
		return members.filter((x) => {
			let key = `${x.account_type}$$${x.account}`
			return (
				selectUsersAccount$$AccountType.includes(key) ||
				(x.account_type === 5 && selectUsersE164.includes(x.account))
			)
		})
	}
	//vip
	const vipList = useBasicInfoStore.getState().vipList
	useBasicInfoStore.setState({ vipList: refresh(vipList) })
	//dcs
	const dcs_members = useMeetingDcsStore.getState().dcs_members
	useMeetingDcsStore.setState({ dcs_members: refresh(dcs_members) })
	//mix
	const members = useMeetingMixStore.getState().members
	useMeetingMixStore.setState({ members: refresh(members) })
	//poll
	const memberList = useMeetingPollStore.getState().memberList
	useMeetingPollStore.setState({ memberList: refresh(memberList) })
	//追呼
	const keep_calling_members = useMeetingParamsStore.getState().keep_calling_members
	useMeetingParamsStore.setState({ keep_calling_members: refresh(keep_calling_members) })
	//todo vmp vmpPoll tvwall tvwallPoll
	// debugger
	let vmpMembers = useMeetingVmpStore.getState().members
	vmpMembers = vmpMembers.filter((x) => {
		if (x.member_type === 1) {
			let key = `${x.account_type}$$${x.account}`
			return (
				selectUsersAccount$$AccountType.includes(key) ||
				(x.account_type === 5 && selectUsersE164.includes(x.account))
			)
		} else if (x.member_type === 6 && x.poll?.members && x.poll?.members.length > 0) {
			x.poll.members = refresh(x.poll.members)
		}
		return true
	})
	useMeetingVmpStore.setState({ members: vmpMembers })
	/**画面合成刷新轮询列表*/
	let vmpPollMembers = useMeetingVmpStore.getState().poll?.members
	if (vmpPollMembers) {
		vmpPollMembers = refresh(vmpPollMembers)
		useMeetingVmpStore.setState({ pollMembers: vmpPollMembers })
	}
	refreshTvwallMembers()
}

/**级联方式改变 */
export async function changeCascadeInUser(isCascade: boolean) {
	if (isCascade) {
		//需要排序，可能存在会议的排序被改变
		const tree = useUserAllStore.getState().tree
		const meetings = tree.filter((x) => x.mcc.account_type === 10)
		let allUsers = [...tree.filter((x) => x.mcc.account_type !== 10), ...meetings]
		//设置搜索
		const keywords = useUserStore.getState().keywords
		setSearchStatusInAll(allUsers, keywords)
		useUserAllStore.setState({ tree: allUsers })

		//请求下级，因为可能一开始没有获取过下级数据
		const cascades = meetings.filter((x) => !x.attr.isSimpleCascade).map((x) => x.mcc.account)
		if (cascades.length > 0) {
			await setSubCascade(cascades)
		}
	} else {
		//非级联情况：把顶层所有展开的会议关上，这样转平铺就不会有下级显示
		const tree = useUserAllStore.getState().tree
		let uuids: string[] = []
		for (const item of tree) {
			item.status.isOpen = false
			uuids.push(item.uuid)
		}
		//移除所有下级会议的常用终端(顶级存在的保留)；互动不用管因为互动只有本级
		const often = useUserOftenStore.getState().list
		let result = often.filter((x) => uuids.includes(x.uuid))

		useUserOftenStore.setState({ list: result })

		let curUuids = result.map((x) => x.uuid)
		getItemInAll(tree, (item) => {
			if (curUuids.includes(item.uuid)) {
				item.status.isOften = true
			} else {
				item.status.isOften = false
			}
		})
		useUserAllStore.setState({ tree: [...tree] })
	}

	//最后，设置发言方，管理方
	changeSpeakerManger()
}

/**新建、新建模板初始化 */
export const userInit = ({ user, rooms = [] }: { user: UserEntity; rooms?: UserEntity[] }) => {
	let allUsers: UserModel[] = [user, ...rooms].map((x) => {
		return {
			mcc: x,
			status: {
				checked: false,
				isOpen: false,
				isMatchSearch: true,
				isOften: false,
				isInteractive: false, //设置 interactive 标志;
			},
			attr: {
				isSimpleCascade: false,
				actualUuid: `${x.account_type}$$${x.account}`,
			},
			uuid: `${x.account_type}$$${x.account}`,
			nestingLevel: 0,
			parentId: '',
			children: [],
		}
	})
	//设置搜索
	const keywords = useUserStore.getState().keywords
	setSearchStatusInAll(allUsers, keywords)
	useUserAllStore.setState({ tree: allUsers })

	//最后，设置发言方，管理方
	changeSpeakerManger()
}

/**编辑、编辑模板初始化 */
export const userEdit = async ({ all, often }: { all: UserEntity[]; often: UserEntity[] }) => {
	//给的都是本级，顺序一定对
	const uuids = often.map((x) => `${x.account_type}$$${x.account}`)
	let allUsers: UserModel[] = all.map((x) => {
		let isInOften = uuids.includes(`${x.account_type}$$${x.account}`)
		return {
			mcc: x,
			status: {
				checked: false,
				isOpen: false,
				isMatchSearch: true,
				isOften: isInOften,
				isInteractive: !!x.interactive_mt, //设置 interactive 标志;
			},
			attr: {
				isSimpleCascade: false,
				actualUuid: `${x.account_type}$$${x.account}`,
			},
			uuid: `${x.account_type}$$${x.account}`,
			nestingLevel: 0,
			parentId: '',
			children: [],
		}
	})
	//设置搜索
	const keywords = useUserStore.getState().keywords
	setSearchStatusInAll(allUsers, keywords)
	useUserAllStore.setState({ tree: allUsers })

	if (useBasicInfoStore.getState().superMtNum) {
		let list = TranslatorAllToSimple(allUsers.filter((x) => x.status.isInteractive))
		setSearchStatusInSimple(list, keywords)
		useUserInteractiveStore.setState({ list })
	} else {
		let list = often.map((x) => ({
			mcc: x,
			status: {
				checked: false,
				isMatchSearch: true,
			},
			uuid: `${x.account_type}$$${x.account}`,
			parentId: x.conf_e164 || '',
		}))
		setSearchStatusInSimple(list, keywords)
		useUserOftenStore.setState({ list })
	}

	//合并级联请求下级
	const curIsCascade = useMeetingParamsStore.getState().simpleCascade === 1
	const cascades = allUsers
		.filter((x) => x.mcc.account_type === 10 && !x.attr.isSimpleCascade)
		.map((x) => x.mcc.account)
	if (curIsCascade && cascades.length > 0) {
		await setSubCascade(cascades)
	}

	//编辑、模板导入时候，需要 刷新外面list字段
	refreshList()

	//最后，设置发言方，管理方
	changeSpeakerManger()
}

/**导入模板 */
export const userImport = ({ all, often }: { all: UserEntity[]; often: UserEntity[] }) => {
	//导入模板需要保留原来的会议室，除非是例会
	let rooms: UserEntity[] = []
	if (!useBasicInfoStore.getState().meetingFormular) {
		const tree = useUserAllStore.getState().tree
		rooms = tree.filter((x) => x.mcc.account_type === 2).map((x) => x.mcc)
	}
	//排好序
	let _all = [...all.filter((x) => x.account_type !== 10), ...rooms, ...all.filter((x) => x.account_type === 10)]
	userEdit({ all: _all, often })
}
